#!/usr/bin/env python3
"""
工具注册中心
"""

import logging
from typing import Dict, List, Any, Optional, Type
from .tool import Tool

logger = logging.getLogger(__name__)

class ToolRegistry:
    """工具注册中心"""
    
    def __init__(self):
        self.tools: Dict[str, Tool] = {}
        self.categories: Dict[str, List[str]] = {
            "analysis": [],      # 分析工具
            "geography": [],     # 地理工具
            "search": [],        # 搜索工具
            "ai": [],           # AI工具
            "system": [],       # 系统工具
            "external": []      # 外部API工具
        }
        self.tool_metadata: Dict[str, Dict[str, Any]] = {}
    
    def register_tool(self, tool: Tool, category: str = "general", 
                     tags: List[str] = None, enabled: bool = True) -> bool:
        """注册工具"""
        try:
            if tool.name in self.tools:
                logger.warning(f"工具 {tool.name} 已存在，将被覆盖")
            
            self.tools[tool.name] = tool
            
            # 添加到分类
            if category in self.categories:
                if tool.name not in self.categories[category]:
                    self.categories[category].append(tool.name)
            else:
                # 创建新分类
                self.categories[category] = [tool.name]
            
            # 保存元数据
            self.tool_metadata[tool.name] = {
                "category": category,
                "tags": tags or [],
                "enabled": enabled,
                "registered_at": self._get_timestamp()
            }
            
            logger.info(f"工具已注册: {tool.name} (分类: {category})")
            return True
            
        except Exception as e:
            logger.error(f"工具注册失败: {tool.name}, 错误: {e}")
            return False
    
    def unregister_tool(self, tool_name: str) -> bool:
        """注销工具"""
        try:
            if tool_name not in self.tools:
                return False
            
            # 从分类中移除
            for category, tools in self.categories.items():
                if tool_name in tools:
                    tools.remove(tool_name)
            
            # 删除工具和元数据
            del self.tools[tool_name]
            if tool_name in self.tool_metadata:
                del self.tool_metadata[tool_name]
            
            logger.info(f"工具已注销: {tool_name}")
            return True
            
        except Exception as e:
            logger.error(f"工具注销失败: {tool_name}, 错误: {e}")
            return False
    
    def get_tool(self, tool_name: str) -> Optional[Tool]:
        """获取工具"""
        return self.tools.get(tool_name)
    
    def get_tools_by_category(self, category: str) -> List[str]:
        """按分类获取工具列表"""
        return self.categories.get(category, [])
    
    def get_all_tools(self) -> Dict[str, Tool]:
        """获取所有工具"""
        return self.tools.copy()
    
    def get_enabled_tools(self) -> Dict[str, Tool]:
        """获取启用的工具"""
        enabled_tools = {}
        for name, tool in self.tools.items():
            if self.tool_metadata.get(name, {}).get("enabled", True):
                enabled_tools[name] = tool
        return enabled_tools
    
    def get_tool_schema(self, tool_name: str) -> Optional[Dict[str, Any]]:
        """获取工具调用模式"""
        tool = self.get_tool(tool_name)
        if tool:
            return tool.get_schema()
        return None
    
    def get_tools_for_intent(self, intent: str) -> List[str]:
        """根据用户意图推荐工具"""
        intent_mapping = {
            "日志分析": ["parse_logs", "count_errors", "analyze_patterns"],
            "地理相关": ["amap_geocoding", "amap_weather", "amap_poi"],
            "搜索查询": ["google_search", "stackoverflow_search", "github_search"],
            "天气查询": ["amap_weather"],
            "位置服务": ["amap_geocoding", "amap_poi"],
            "技术搜索": ["google_search", "stackoverflow_search", "github_search"]
        }
        return intent_mapping.get(intent, ["google_search"])
    
    def search_tools(self, keyword: str) -> List[str]:
        """搜索工具"""
        matching_tools = []
        keyword_lower = keyword.lower()
        
        for tool_name, metadata in self.tool_metadata.items():
            # 搜索工具名
            if keyword_lower in tool_name.lower():
                matching_tools.append(tool_name)
                continue
            
            # 搜索描述
            tool = self.get_tool(tool_name)
            if tool and keyword_lower in tool.description.lower():
                matching_tools.append(tool_name)
                continue
            
            # 搜索标签
            for tag in metadata.get("tags", []):
                if keyword_lower in tag.lower():
                    matching_tools.append(tool_name)
                    break
        
        return list(set(matching_tools))  # 去重
    
    def enable_tool(self, tool_name: str) -> bool:
        """启用工具"""
        if tool_name in self.tool_metadata:
            self.tool_metadata[tool_name]["enabled"] = True
            return True
        return False
    
    def disable_tool(self, tool_name: str) -> bool:
        """禁用工具"""
        if tool_name in self.tool_metadata:
            self.tool_metadata[tool_name]["enabled"] = False
            return True
        return False
    
    def get_tool_stats(self) -> Dict[str, Any]:
        """获取工具统计信息"""
        enabled_count = sum(1 for meta in self.tool_metadata.values() if meta.get("enabled", True))
        
        return {
            "total_tools": len(self.tools),
            "enabled_tools": enabled_count,
            "disabled_tools": len(self.tools) - enabled_count,
            "categories": {cat: len(tools) for cat, tools in self.categories.items()},
            "tools": list(self.tools.keys()),
            "metadata": self.tool_metadata
        }
    
    def _get_timestamp(self) -> str:
        """获取当前时间戳"""
        from datetime import datetime
        return datetime.now().isoformat()
